package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录认证拦截器
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求登录信息中的cookie
        Cookie cookie = CookieUtil.getCookie(request, UserInfoKeyPrefix.USER_INFO_COOKIE_NAME);
        UserInfo userInfo = null;
        //判断reids是否有登录的信息, 有则获取用户信息userInfo
        if(cookie != null){
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, cookie.getValue());
        }
        //判断是否请求访问的是映射方法, 是的话判断是否用户信息存在, 不存在跳转到登录界面
        if (handler instanceof HandlerMethod){
            HandlerMethod h = (HandlerMethod) handler;
            if(h.hasMethodAnnotation(RequireLogin.class)){
                if (userInfo == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
